package com.demo.util.excel.utils;

import com.demo.util.excel.enums.ExcelDataType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

import java.math.BigDecimal;
import java.util.Date;

public class ExcelCellValueUtil {

    /**
     * 设置单元格内容
     */
    public static void setDataCellValue(Cell cell, ExcelDataType dataType, Object value) {
        if (value == null) {
            return;
        }
        dataType = dataType == null ? ExcelDataType.STRING : dataType;
        switch (dataType) {
            case INTEGER:
                if (value instanceof String) {
                    try {
                        cell.setCellValue(Double.parseDouble((String) value));
                    } catch (Exception e) {
                        throw new RuntimeException("设置单元格数字数据格式化失败：" + value);
                    }
                } else if (value instanceof Number) {
                    cell.setCellValue(((Number) value).doubleValue());
                } else if (value instanceof Date) {
                    cell.setCellValue(((Date) value));
                }
                break;
            default:
                cell.setCellValue(value.toString());
                break;
        }
    }

    /**
     * 读取单元格内容
     */
    public static String getCellStringValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        CellType cellType = cell.getCellType();
        switch (cellType) {
            case STRING: return cell.getStringCellValue();
            case NUMERIC: return BigDecimal.valueOf(cell.getNumericCellValue()).stripTrailingZeros().toPlainString();
        }
        return null;
    }

}
